package cn.itsource.pet.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.itsource.basic.service.BaseServiceImpl;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.GetRedisLoginVoUtil;
import cn.itsource.pet.mapper.OrderPetAcquisitionMapper;
import cn.itsource.pet.mapper.PetMapper;
import cn.itsource.pet.mapper.SearchMasterMsgMapper;
import cn.itsource.pet.pojo.domain.OrderPetAcquisition;
import cn.itsource.pet.pojo.domain.Pet;
import cn.itsource.pet.pojo.domain.SearchMasterMsg;
import cn.itsource.pet.pojo.dto.OrderPetAcquisitionDto;
import cn.itsource.pet.query.OrderPetAcquisitionQuery;
import cn.itsource.pet.service.IOrderPetAcquisitionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
*
*/
@Service
public class OrderPetAcquisitionServiceImpl extends BaseServiceImpl<OrderPetAcquisition, OrderPetAcquisitionQuery> implements IOrderPetAcquisitionService {

    @Autowired
    private SearchMasterMsgMapper msgMapper;

    @Autowired
    private OrderPetAcquisitionMapper opaMapper;

    @Autowired
    private PetMapper petMapper;

    /**
     * 生成宠物订单  alt+enter
     */
    @Override
    @Transactional
    public AjaxResult createOrder(OrderPetAcquisitionDto orderDto) {

        //1.修改msg表的字段 state shop_id
        SearchMasterMsg msg = new SearchMasterMsg();
        msg.setId(orderDto.getId()); //主键id
        msg.setState(1);//已接单
        msg.setShopId(GetRedisLoginVoUtil.getShopId());
        //1.1msg表维护字段完毕
        msgMapper.updateByPrimaryKeySelective(msg);

        //2.维护线下收购表
        //2.1查询msg表数据
        SearchMasterMsg dbMsg = msgMapper.selectByPrimaryKey(orderDto.getId());

        OrderPetAcquisition opa = BeanUtil.copyProperties(dbMsg, OrderPetAcquisition.class);
        opa.setId(null);
        opa.setState(0);
        opa.setDigest(orderDto.getNote());
        opa.setEmpId(orderDto.getEmployeeId()); //店铺接单员工ide
        opa.setMsgId(orderDto.getId());//msg的id作为这张表的外键

        opaMapper.insert(opa); //注意：pet_id还没存

        //3.入库t_pet表，宠物买卖表
        Pet pet = BeanUtil.copyProperties(dbMsg, Pet.class);
        pet.setId(null);
        pet.setSaleprice(dbMsg.getPrice().doubleValue()*2.0);
        pet.setState(0L); //默认下架状态
        pet.setCreateTime(new Date());
        pet.setTypeId(dbMsg.getPetType());
        pet.setUserId(null);
        pet.setCostprice(dbMsg.getPrice().doubleValue()*1.6);
        pet.setResourceType("1");//线下收购
        //3.1宠物入库
        petMapper.insert(pet);

        //4.维护opa的pet_id字段
        opa.setPetId(pet.getId());
        opaMapper.updateByPrimaryKey(opa);

        //返回成功
        return AjaxResult.createSuccess();
    }
}
